﻿//////////////////////////////////////////////
/// 实现http通信
//////////////////////////////////////////////
#include "HttpServer.h"
#include <QDebug>
#include <QHttpHeaders>
#include <QHttpServer>
#include <QHttpServerRequest>
#include <QHttpServerResponse>
#include <QTcpServer>
#include "ShowWidget.h"
#include "friend.qpb.h"
#include "log.h"
#include "message_storage.qpb.h"
#include "message_transmit.qpb.h"
#include "user.qpb.h"
#include "file.qpb.h"
#include "speech_recognition.qpb.h"
HttpServer* HttpServer::instance = nullptr;

using namespace chat;

HttpServer* HttpServer::get_instance()
{
    if (instance == nullptr) {
        instance = new HttpServer();
    }
    return instance;
}

/// @brief 监听HTTP请求
/// @return
bool HttpServer::init()
{
    /* 先设置路由 */
    /* 返回 pong */
    http_server.route("/ping", [this](const QHttpServerRequest& request) {
        LOG() << "Received ping request from" << request.remoteAddress().toString();
        show_widget->ADD_LOG_MESSAGE("Received ping request from " + request.remoteAddress().toString());
        return "pong";
    });
    /* 获取个人信息 */
    http_server.route("/service/user/get_user_info", [this](const QHttpServerRequest& request) {
        return handle_get_user_info(request);
    });
    /* 获取好友列表 */
    http_server.route("/service/friend/get_friend_list", [this](const QHttpServerRequest& request) {
        return handle_get_friend_list(request);
    });
    /* 获取会话列表 */
    http_server.route("/service/friend/get_chat_session_list", [this](const QHttpServerRequest& request) {
        return handle_get_chat_session_list(request);
    });
    /* 获取好友申请列表 */
    http_server.route("/service/friend/get_pending_friend_events", [this](const QHttpServerRequest& request) {
        return handle_get_friend_apply_list(request);
    });
    /* 获取某一个会话的最近n条消息 */
    http_server.route("/service/message_storage/get_recent", [this](const QHttpServerRequest& request) {
        return handle_get_recent_msgs(request);
    });
    /* 发送消息 */
    http_server.route("/service/message_transmit/new_message", [this](const QHttpServerRequest& request) {
        return handle_send_msg(request);
    });
    /* 设置用户昵称 */
    http_server.route("/service/user/set_nickname", [this](const QHttpServerRequest& request) {
        return handle_set_nickname(request);
    });
    /* 设置用户个性签名 */
    http_server.route("/service/user/set_description", [this](const QHttpServerRequest& request) {
        return handle_set_desc(request);
    });
    /* 设置用户手机号 */
    http_server.route("/service/user/set_phone", [this](const QHttpServerRequest& request) {
        return handle_set_phone(request);
    });
    /* 获得手机验证码 */
    http_server.route("/service/user/get_phone_verify_code", [this](const QHttpServerRequest& request) {
        return handle_get_phone_verify_code(request);
    });
    /* 设置用户头像 */
    http_server.route("/service/user/set_avatar", [this](const QHttpServerRequest& request) {
        return handle_set_avatar(request);
    });
    /* 删除好友 */
    http_server.route("/service/friend/remove_friend", [this](const QHttpServerRequest& request) {
        return handle_delete_friend(request);
    });
    /* 好友申请处理 */
    http_server.route("/service/friend/add_friend_apply", [this](const QHttpServerRequest& request) {
        return handle_add_friend(request);
    });
    /* 同意好友申请 */
    http_server.route("/service/friend/add_friend_process", [this](const QHttpServerRequest& request) {
        return handle_add_friend_process(request);
    });
    /* 创建群聊处理 */
    http_server.route("/service/friend/create_chat_session", [this](const QHttpServerRequest& request) {
        return handle_create_chat_session(request);
    });
    /* 获取群聊群员列表 */
    http_server.route("/service/friend/get_chat_session_member", [this](const QHttpServerRequest& request) {
        return handle_get_chat_session_member(request);
    });
    /* 处理搜索用户请求 */
    http_server.route("/service/friend/search_friend", [this](const QHttpServerRequest& request) {
        return handle_search_user(request);
    });
    /* 搜索历史消息 */
    http_server.route("/service/message_storage/search_history", [this](const QHttpServerRequest& request) {
        return handle_search_history(request);
    });
    /* 根据时间搜索历史消息 */
    http_server.route("/service/message_storage/get_history", [this](const QHttpServerRequest& request) {
        return handle_search_history_by_time(request);
    });
    /* 用户名密码登录 */
    http_server.route("/service/user/username_login", [this](const QHttpServerRequest& request) {
        return handle_login_by_username(request);
    });
    /* 用户名密码注册 */
    http_server.route("/service/user/username_register", [this](const QHttpServerRequest& request) {
        return handle_register_by_username(request);
    });
    /* 手机号登录 */
    http_server.route("/service/user/phone_login", [this](const QHttpServerRequest& request) {
        return handle_login_by_phone(request);
    });
    /* 手机号注册 */
    http_server.route("/service/user/phone_register", [this](const QHttpServerRequest& request) {
        return handle_register_by_phone(request);
    });
    /* 获取单个文件的内容 */
    http_server.route("/service/file/get_single_file", [this](const QHttpServerRequest& request) {
        return handle_get_file(request);
    });
    /* 语音识别 */
    http_server.route("/service/speech/recognition", [this](const QHttpServerRequest& request) {
        return handle_speech_recognition(request);
    });
    /* 创建并配置TCP服务器 */
    tcp_server = new QTcpServer(&http_server);  // 指定父对象为该 http_server
    if (!tcp_server->listen(QHostAddress::Any, HTTP_PORT)) {
        LOG() << "Failed to start TCP server:" << tcp_server->errorString();
        show_widget->ADD_LOG_MESSAGE("Failed to start TCP server:" + tcp_server->errorString());
        return false;
    }
    if (!http_server.bind(tcp_server)) {
        LOG() << "Failed to bind HTTP server to TCP server";
        show_widget->ADD_LOG_MESSAGE("Failed to bind HTTP server to TCP server");
        return false;
    }
    LOG() << "HTTP server started on port" << HTTP_PORT;
    show_widget->ADD_LOG_MESSAGE("HTTP server started on port: " + QString::number(HTTP_PORT));
    return true;
}

HttpServer::HttpServer()
    : tcp_server(nullptr)
{
    show_widget = ShowWidget::get_instance();
}

HttpServer::~HttpServer()
{
    if (tcp_server) {
        tcp_server->close();
        delete tcp_server;
    }
}

/// @brief 读取文件内容
/// @return 是否读取成功
///     @retval "" 表示读取失败
///     @retval 不是上面的情况表示读取成功
QByteArray HttpServer::read_file(const QString& file_name)
{
    QFile file(file_name);
    bool  ok = file.open(QIODevice::ReadOnly);
    if (ok == false) {
        LOG() << "open file: " << file_name << "error! why: " << file.errorString();
        show_widget->ADD_LOG_MESSAGE("open file: " + file_name + " error! why: " + file.errorString());
        file.close();
        return QByteArray();
    }
    QByteArray data = file.readAll();
    file.close();
    return data;
}

/// @brief 获得当前的时间戳
qint64 HttpServer::get_current_time_stamp()
{
    return QDateTime::currentSecsSinceEpoch();
}

/// @brief 发送数据到客户端
QHttpServerResponse HttpServer::make_http_response(const QByteArray& data)
{
    auto         http_resp = QHttpServerResponse(data, QHttpServerResponse::StatusCode::Ok);
    QHttpHeaders headers;
    headers.append(QHttpHeaders::WellKnownHeader::ContentType, "application/x-protobuf");
    http_resp.setHeaders(headers);
    return http_resp;
}

/// @brief 工具方法: 创建一个UserInfo对象
std::unique_ptr<UserInfo> HttpServer::make_user_info(const QByteArray& avatar, const QString& user_id,
                                                     const QString& description, const QString& nick_name,
                                                     const QString& phone)
{
    auto user_info = std::make_unique<UserInfo>();
    user_info->setAvatar(avatar);
    user_info->setUserId(user_id);
    user_info->setDescription(description);
    user_info->setNickname(nick_name);
    user_info->setPhone(phone);
    /* C++11 以后，函数按值返回局部变量时，
    编译器会自动触发 返回值优化（RVO） 或 移动构造，不会调用拷贝构造函数，
    也不会违反 unique_ptr 的“唯一所有权”语义。 */
    return user_info;
}

/// @brief 工具方法: 创建一个消息类型，可以是文本消息，图片消息，文件消息，语音消息
std::unique_ptr<MessageInfo> HttpServer::make_message_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar)
{
    auto message_info = std::make_unique<MessageInfo>();
    message_info->setMessageId(QString::number(index) + "2000");  // random
    message_info->setChatSessionId(chat_session_id);
    message_info->setTimestamp(get_current_time_stamp());
    message_info->setSender(*make_user_info(avatar, user_id,
                                            "desc..." + QString::number(index), "FooBar", "114514"));
    MessageContent message_content;
    message_content.setMessageType(MessageTypeGadget::MessageType::STRING);
    StringMessageInfo string_message_info;
    QString           text_message = QStringLiteral(
                               "你好") +
                           QString::number(index);
    string_message_info.setContent(text_message);
    message_content.setStringMessage(string_message_info);
    message_info->setMessage(message_content);
    return message_info;
}

/// @brief 生成一个图片消息类型
std::unique_ptr<MessageInfo> HttpServer::make_image_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar)
{
    auto message_info = std::make_unique<MessageInfo>();
    message_info->setMessageId(QString::number(index) + "2000");  // random
    message_info->setChatSessionId(chat_session_id);
    message_info->setTimestamp(get_current_time_stamp());
    message_info->setSender(*make_user_info(avatar, user_id,
                                            "desc..." + QString::number(index), "FooBar", "114514"));
    MessageContent message_content;
    message_content.setMessageType(MessageTypeGadget::MessageType::IMAGE);
    ImageMessageInfo image_message_info;
    image_message_info.setFileId("test_image");
    message_content.setImageMessage(image_message_info);
    message_info->setMessage(message_content);
    return message_info;
}

/// @brief 生成一个文件消息类型
std::unique_ptr<MessageInfo> HttpServer::make_file_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar)
{
    auto message_info = std::make_unique<MessageInfo>();
    message_info->setMessageId(QString::number(index) + "3000");  // random
    message_info->setChatSessionId(chat_session_id);
    message_info->setTimestamp(get_current_time_stamp());
    message_info->setSender(*make_user_info(avatar, user_id,
                                            "desc..." + QString::number(index), "FooBar", "114514"));
    MessageContent message_content;
    message_content.setMessageType(MessageTypeGadget::MessageType::FILE);
    FileMessageInfo file_message_info;
    file_message_info.setFileId("test_file");
    file_message_info.setFileName("test.txt");
    message_content.setFileMessage(file_message_info);
    message_info->setMessage(message_content);
    return message_info;
}

std::unique_ptr<MessageInfo> HttpServer::make_speech_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar)
{
    auto message_info = std::make_unique<MessageInfo>();
    message_info->setMessageId(QString::number(index) + "4000");  // random
    message_info->setChatSessionId(chat_session_id);
    message_info->setTimestamp(get_current_time_stamp());
    message_info->setSender(*make_user_info(avatar, user_id,
                                            "desc..." + QString::number(index), "FooBar", "114514"));
    MessageContent message_content;
    message_content.setMessageType(MessageTypeGadget::MessageType::SPEECH);
    SpeechMessageInfo speech_message_info;
    speech_message_info.setFileId("test_speech");
    message_content.setSpeechMessage(speech_message_info);
    message_info->setMessage(message_content);
    return message_info;
}


/// @brief 处理/service/user/get_user_info请求
/// 获取个人信息
QHttpServerResponse HttpServer::handle_get_user_info(const QHttpServerRequest& request)
{
    /* 解析请求 */
    chat::GetUserInfoReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received get_user_info request for requestID:" << req.requestId();
    show_widget->ADD_LOG_MESSAGE("Received get_user_info request for requestID:" + req.requestId() +
                                 " loginSessionId: " + req.sessionId());
    /* 构建响应 */
    chat::GetUserInfoRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    resp.setUserInfo(*make_user_info(read_file(":/image/nyaruko.png"),
                                     "100030",
                                     "A character from the anime 'Haiyore! Nyaruko-san'",
                                     "Nyaruko", "18012345678"));
    /* 序列化 */
    QByteArray resp_data = resp.serialize(&serializer);
    /* 发送给客户端 */
    auto         http_resp = QHttpServerResponse(resp_data, QHttpServerResponse::StatusCode::Ok);
    QHttpHeaders headers;
    headers.append(QHttpHeaders::WellKnownHeader::ContentType, "application/x-protobuf");
    http_resp.setHeaders(headers);
    return http_resp;
}

/// @brief 处理/service/friend/get_friend_list请求
/// 获取好友列表
QHttpServerResponse HttpServer::handle_get_friend_list(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetFriendListReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received get_friend_list request for requestID:" << req.requestId();
    show_widget->ADD_LOG_MESSAGE("Received get_friend_list request for requestID:" + req.requestId());
    /* 构建响应 */
    GetFriendListRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<UserInfo>  friend_list;
    const QByteArray avatar = read_file(":/image/vanilla.png");
    for (int i = 1; i <= 20; ++i) {
        friend_list.append(*make_user_info(
            avatar,
            "1000" + QString::number(i),
            "Cute nekogirl " + QString::number(i),
            "Vanilla",
            "123-456-7890"));
    }
    rsp.setFriendList(friend_list);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/get_chat_session_list请求
///        获取会话列表
QHttpServerResponse HttpServer::handle_get_chat_session_list(const QHttpServerRequest& request)
{
    /* 解析请求 */
    chat::GetChatSessionListReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received get_chat_session_list request for requestID:" << req.requestId();
    show_widget->ADD_LOG_MESSAGE("Received get_chat_session_list request for requestID:" + req.requestId());
    /* 构建响应 */
    chat::GetChatSessionListRsp resp;
    resp.setRequestId(req.requestId());
    resp.setSuccess(true);
    resp.setErrmsg("");
    chat::ChatSessionInfo  info;
    QList<ChatSessionInfo> list = resp.chatSessionInfoList();
    /* 构造假的数据, 但是要注意这里的 user_id 要和 handle_get_friend_list 创建的 user_id 一致*/
    const QByteArray avatar = read_file(":/image/chocolate.png");
    for (int i = 1; i <= 30; ++i) {
        if (i <= 15) {
            /* 单聊 */
            info.setSingleChatFriendId("1000" + QString::number(i));
            info.setChatSessionId("5000" + QString::number(i));
            info.setChatSessionName("It's MyGo " + QString::number(i));
            MessageInfo message_info = *make_message_info(i, info.chatSessionId(), "1000" + QString::number(i), avatar);
            info.setPrevMessage(message_info);
            info.setAvatar(avatar);
            list.push_back(info);
        } else {
            /* 群聊 */
            info.setSingleChatFriendId("");
            info.setChatSessionId("5000" + QString::number(i));
            info.setChatSessionName("It's MyGo " + QString::number(i));
            MessageInfo message_info = *make_message_info(i, info.chatSessionId(), "", avatar);
            info.setPrevMessage(message_info);
            info.setAvatar(avatar);
            list.push_back(info);
        }
    }
    resp.setChatSessionInfoList(list);
    /* 序列化 */
    QByteArray resp_data = resp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/get_pending_friend_events请求
/// 获取待处理的好友申请列表
QHttpServerResponse HttpServer::handle_get_friend_apply_list(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetFriendListReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received handle_get_friend_apply_list request for requestID: " << req.requestId();
    show_widget->ADD_LOG_MESSAGE("Received handle_get_friend_apply_list request for requestID: " + req.requestId());
    /* 构建响应 */
    GetPendingFriendEventListRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<FriendEvent> friend_event;
    const QByteArray   avatar = read_file(":/image/nyamu.png");
    for (int i = 0; i < 10; ++i) {
        FriendEvent event;
        event.setEventId("Event " + QString::number(i));
        UserInfo user = *make_user_info(
            avatar,
            "2000" + QString::number(i),
            "Yutenji Nyamu " + QString::number(i),
            "Nyamu",
            "114514");
        event.setSender(user);
        friend_event.append(event);
    }
    rsp.setEvent(friend_event);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/message_storage/get_recent请求
/// 获取指定会话ID的最近N条消息
QHttpServerResponse HttpServer::handle_get_recent_msgs(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetRecentMsgReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received handle_get_recent_msgs request for requestID: " << req.requestId()
          << " chatSessionID: " << req.chatSessionId();
    show_widget->ADD_LOG_MESSAGE("Received handle_get_recent_msgs request for requestID: " +
                                 req.requestId() + " chatSessionID: " + req.chatSessionId());
    /* 构建响应 */
    GetRecentMsgRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<MessageInfo> message_info;
    const QByteArray   avatar = read_file(":/image/defaultAvatar.png");
    /* 新的消息在 list 最后面 */
    for (int i = 1; i <= 30; ++i) {
        /* 这里的 chat_session_id 要在之前 handle_get_chat_session_list() 创建的id一致 */
        // if (i == 1) {
        //     /* 自己的消息 */
        //     MessageInfo message = *make_message_info(i, "5000" + QString::number(i), "10030", avatar);
        //     message_info.append(message);
        // } else {
        MessageInfo message = *make_message_info(i, "5000" + QString::number(i), "1000" + QString::number(i), avatar);
        message_info.append(message);
        //}
    }
    rsp.setMsgList(message_info);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/message_transmit/new_message请求
///        发送消息请求
QHttpServerResponse HttpServer::handle_send_msg(const QHttpServerRequest& request)
{
    /* 解析请求 */
    NewMessageReq req;
    req.deserialize(&serializer, request.body());
    LOG() << "Received handle_send_msg request for requestID: " << req.requestId()
          << " chatSessionID: " << req.chatSessionId();
    show_widget->ADD_LOG_MESSAGE("Received handle_send_msg request for requestID: " + req.requestId() + " chatSessionID: " + req.chatSessionId());
    /* 构建响应 */
    NewMessageRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/user/set_nickname请求
///        设置用户昵称
QHttpServerResponse HttpServer::handle_set_nickname(const QHttpServerRequest& request)
{
    /* 解析请求 */
    SetUserNicknameReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_set_nickname request for requestID: " + req.requestId());
    /* 构建响应 */
    SetUserNicknameRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/user/set_description请求
///        设置用户个性签名
QHttpServerResponse HttpServer::handle_set_desc(const QHttpServerRequest& request)
{
    /* 解析请求 */
    SetUserDescriptionReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_set_desc request for requestID: " + req.requestId());
    /* 构建响应 */
    SetUserDescriptionRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/user/get_phone_verify_code请求
///        获取手机验证码
QHttpServerResponse HttpServer::handle_get_phone_verify_code(const QHttpServerRequest& request)
{
    /* 解析请求 */
    PhoneVerifyCodeReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_get_phone_verify_code request for requestID: " + req.requestId());
    /* 构建响应 */
    PhoneVerifyCodeRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    rsp.setVerifyCodeId("test");  // for test
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/user/set_phone请求
///        设置用户的手机号
QHttpServerResponse HttpServer::handle_set_phone(const QHttpServerRequest& request)
{
    /* 解析请求 */
    SetUserPhoneNumberReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_set_phone request for requestID: " + req.requestId());
    /* 构建响应 */
    SetUserPhoneNumberRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/user/set_avatar请求
///        设置用户头像
QHttpServerResponse HttpServer::handle_set_avatar(const QHttpServerRequest& request)
{
    /* 解析请求 */
    SetUserAvatarReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_set_phone request for requestID: " + req.requestId());
    /* 构建响应 */
    SetUserAvatarRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/remove_friend请求
///        删除好友
QHttpServerResponse HttpServer::handle_delete_friend(const QHttpServerRequest& request)
{
    /* 解析请求 */
    FriendRemoveReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_delete_friend request for requestID: " + req.requestId());
    /* 构建响应 */
    FriendRemoveRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/add_friend_apply请求
///        处理添加好友申请
QHttpServerResponse HttpServer::handle_add_friend(const QHttpServerRequest& request)
{
    /* 解析请求 */
    FriendAddReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_add_friend request for requestID: " + req.requestId());
    /* 构建响应 */
    FriendAddRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    rsp.setNotifyEventId("");
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/add_friend_process请求
///        决定是否添加好友申请
QHttpServerResponse HttpServer::handle_add_friend_process(const QHttpServerRequest& request)
{
    /* 解析请求 */
    FriendAddProcessReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_add_friend_process request for requestID: " + req.requestId());
    /* 构建响应 */
    FriendAddProcessRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/chat_session/create请求
///        创建群聊
QHttpServerResponse HttpServer::handle_create_chat_session(const QHttpServerRequest& request)
{
    /* 解析请求 */
    ChatSessionCreateReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_create_chat_session request for requestID: " + req.requestId());
    /* 构建响应 */
    ChatSessionCreateRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    // rsp.setChatSessionInfo(ChatSessionInfo());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/get_chat_session_member
///        获取群聊成员
QHttpServerResponse HttpServer::handle_get_chat_session_member(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetChatSessionMemberReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_get_chat_session_member request for requestID: " + req.requestId());
    /* 构建响应 */
    GetChatSessionMemberRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<UserInfo>  member_list;
    const QByteArray avatar = read_file(":/image/cinnamon.png");
    for (int i = 1; i <= 20; ++i) {
        member_list.append(*make_user_info(
            avatar,
            "1000" + QString::number(i),
            "Cute nekogirl " + QString::number(i),
            "cinnamon",
            "123-456-7890"));
    }
    rsp.setMemberInfoList(member_list);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/friend/search_friend请求
///        搜索用户
QHttpServerResponse HttpServer::handle_search_user(const QHttpServerRequest& request)
{
    /* 解析请求 */
    FriendSearchReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_search_user request for requestID: " + req.requestId());
    /* 构建响应 */
    FriendSearchRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<UserInfo>  member_list;
    const QByteArray avatar = read_file(":/image/Yachiho.jpg");
    for (int i = 1; i <= 20; ++i) {
        member_list.append(*make_user_info(
            avatar,
            "1000" + QString::number(i),
            "Golden Hour!!!" + QString::number(i),
            "cinnamon",
            "123-456-7890"));
    }
    rsp.setUserInfo(member_list);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/message_storage/search_history请求
///        根据关键字获取搜索的消息列表
QHttpServerResponse HttpServer::handle_search_history(const QHttpServerRequest& request)
{
    /* 解析请求 */
    MsgSearchReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_search_history request for requestID: " + req.requestId());
    /* 构建响应 */
    MsgSearchRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<MessageInfo> message_info;
    const QByteArray   avatar = read_file(":/image/defaultAvatar.png");
    for (int i = 1; i <= 30; ++i) {
        MessageInfo message = *make_message_info(i, "5000" + QString::number(i), "1000" + QString::number(i), avatar);
        message_info.append(message);
    }
    MessageInfo image_info = *make_image_info(
        31, "50001", "10099", read_file(":/image/defaultAvatar.png"));  // 发送到第一个会话聊天当中
    message_info.append(image_info);
    MessageInfo file_info = *make_file_info(
        32, "50001", "10099", read_file(":/image/defaultAvatar.png"));
    message_info.append(file_info);
    MessageInfo speech_info = *make_speech_info(
        33, "50001", "10099", read_file(":/image/defaultAvatar.png"));
    message_info.append(speech_info);
    rsp.setMsgList(message_info);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/message_storage/get_history请求
///        根据时间获取搜索消息列表
QHttpServerResponse HttpServer::handle_search_history_by_time(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetRecentMsgReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_search_history_by_time request for requestID: " + req.requestId());
    /* 构建响应 */
    GetRecentMsgRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    QList<MessageInfo> message_info;
    const QByteArray   avatar = read_file(":/image/cinnamon.png");
    for (int i = 1; i <= 30; ++i) {
        MessageInfo message = *make_message_info(i, "5000" + QString::number(i), "1000" + QString::number(i), avatar);
        message_info.append(message);
    }
    rsp.setMsgList(message_info);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 通过用户名密码登录
QHttpServerResponse HttpServer::handle_login_by_username(const QHttpServerRequest& request)
{
    /* 解析请求 */
    UserLoginReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_login_by_username request for requestID: " + req.requestId());
    /* 构建响应 */
    UserLoginRsp rsp;
    // rsp.setSuccess(false);
    // rsp.setErrmsg("失败了失败了失败了...");
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    rsp.setLoginSessionId("aaaaabbbbb123");
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 通过用户名密码注册
QHttpServerResponse HttpServer::handle_register_by_username(const QHttpServerRequest& request)
{
    /* 解析请求 */
    UserRegisterReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_register_by_username request for requestID: " + req.requestId());
    /* 构建响应 */
    UserRegisterRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 通过手机号登录
QHttpServerResponse HttpServer::handle_login_by_phone(const QHttpServerRequest& request)
{ 
    /* 解析请求 */
    PhoneLoginReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_login_by_phone request for requestID: " + req.requestId());
    /* 构建响应 */
    PhoneLoginRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    rsp.setLoginSessionId("cccccddddd456");
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 通过手机号注册
QHttpServerResponse HttpServer::handle_register_by_phone(const QHttpServerRequest& request)
{
    /* 解析请求 */
    PhoneRegisterReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_register_by_phone request for requestID: " + req.requestId());
    /* 构建响应 */
    PhoneRegisterRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 处理/service/file/get_file请求
/// 	   获取单个文件的内容
QHttpServerResponse HttpServer::handle_get_file(const QHttpServerRequest& request)
{
    /* 解析请求 */
    GetSingleFileReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_get_file request for requestID: " + req.requestId());
    GetSingleFileRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    FileDownloadData file_data;
    file_data.setFileId(req.fileId());
    /* 根据不同的文件ID构建响应, 只是用于测试的 file_id */
    if (req.fileId() == "test_image") {
        file_data.setFileContent(read_file(":/image/Yachiho.jpg"));
    } else if (req.fileId() == "test_file") {
        file_data.setFileContent(read_file(":/files/test.txt"));
    } else if (req.fileId() == "test_speech") {
        file_data.setFileContent(read_file(":/files/test.speech"));
    } else {
        show_widget->ADD_LOG_MESSAGE("Received handle_get_file request for unknown fileID: " + req.fileId());
    }
    rsp.setFileData(file_data);
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}

/// @brief 进行语音识别
QHttpServerResponse HttpServer::handle_speech_recognition(const QHttpServerRequest& request)
{
    /* 解析请求 */
    SpeechRecognitionReq req;
    req.deserialize(&serializer, request.body());
    show_widget->ADD_LOG_MESSAGE("Received handle_speech_recognition request for requestID: " + req.requestId());
    SpeechRecognitionRsp rsp;
    rsp.setSuccess(true);
    rsp.setErrmsg("");
    rsp.setRequestId(req.requestId());
    rsp.setRecognitionResult("你好你好你好, 这是一段测试文本, 来自语音识别");
    /* 序列化 */
    QByteArray resp_data = rsp.serialize(&serializer);
    /* 发送给客户端 */
    return make_http_response(resp_data);
}
